/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

 // migrate 包用于迁移已订阅用户
package migrate

import (
	"net/http"
	"gitee.com/tugoer/orivil/wechat"
	"io/ioutil"
	"encoding/json"
)

// 获得已订阅用户列表
func GetSubscribeUsers(tokenProvider func() (token string), walk func(openids []string) error) error {
	return next(tokenProvider, "", walk)
}

func next(tokenProvider func() (token string), nextOpenID string, walk func(openids []string) error) (err error) {
	u := "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+tokenProvider()
	if nextOpenID != "" {
		u += "&next_openid=" + nextOpenID
	}
	res, err := http.Get(u)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	data, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return err
	}
	r := &response{}
	err = json.Unmarshal(data, r)
	if err != nil {
		return err
	}
	if r.ErrCode != 0 {
		return r.Error
	}
	err = walk(r.Data.Openid)
	if err != nil {
		return err
	}
	if r.NextOpenid != "" {
		err := next(tokenProvider, r.NextOpenid, walk)
		if err != nil {
			return err
		}
	}
	return nil
}

type response struct {
	Total int `json:"total"`
	Count int `json:"count"`
	Data struct{Openid []string `json:"openid"`} `json:"data"`
	NextOpenid string `json:"next_openid"`
	wechat.Error
}